package org.metaverse.h2;

import java.sql.Connection;
import java.sql.Statement;
import java.util.Hashtable;

import org.h2.jdbcx.JdbcConnectionPool;
import org.metaverse.h2.cache.H2ValueCache;
import org.metaverse.h2.sql.SQL;
import org.metaverse.warehouse.Admin;
import org.metaverse.warehouse.BulkUploader;
import org.metaverse.warehouse.ContextControl;
import org.metaverse.warehouse.Fetcher;
import org.metaverse.warehouse.Solver;
import org.metaverse.warehouse.Uploader;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

/**
 * 
 * @author vjache
 *
 */
public class Activator implements BundleActivator {

	private static BundleContext _context;
	
	private JdbcConnectionPool _connPool;

	static BundleContext getContext() {
		return _context;
	}
	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	@SuppressWarnings("unchecked")
	public void start(BundleContext bundleContext) throws Exception {
		Activator._context = bundleContext;
		
		final SQL sql = new SQL("PUBLIC");
		
		_connPool = JdbcConnectionPool.create(
	             "jdbc:h2:~/mvwh", "sa", "sa");
		_connPool.setMaxConnections(64);
		
		final Connection conn = _connPool.getConnection();
		final Statement statem = conn.createStatement();
		statem.execute(sql.getDDL());
		statem.close();
		conn.close();
		
		final H2ValueCache valueCache = new H2ValueCache(_connPool,sql);
		
		_context.registerService(
				Admin.class.getName(), 
				new AdminImpl(_connPool), 
				new Hashtable());
		
		_context.registerService(
				ContextControl.class.getName(), 
				new ContextControlImpl(_connPool), 
				new Hashtable());
		
		_context.registerService(
				Fetcher.class.getName(), 
				new FetcherImpl(_connPool, valueCache), 
				new Hashtable());
		
		_context.registerService(
				BulkUploader.class.getName(), 
				new BulkUploaderImpl(sql,_connPool), 
				new Hashtable());
		
		_context.registerService(
				Uploader.class.getName(), 
				new UploaderImpl(sql,_connPool,valueCache), 
				new Hashtable());
		
		_context.registerService(
				Solver.class.getName(), 
				new SolverImpl(_connPool), 
				new Hashtable());
	}

	/*
	 * (non-Javadoc)
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext bundleContext) throws Exception {
		Activator._context = null;
		_connPool.dispose();
		_connPool = null;
	}

}
